package com.acmen.easyapi.executor;

import com.acmen.easyapi.model.App;
import com.acmen.easyapi.model.Environment;
import com.acmen.easyapi.repository.AppRepository;
import com.acmen.easyapi.repository.EnvironmentRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 应用同步执行器
 * @author acmen
 */
@Component
public class AppSyncExe {
    @Resource
    private AppRepository appRepository;
    @Resource
    private ApiSaveExe apiSaveExe;
    @Resource
    private EnvironmentRepository environmentRepository;


    public void sync(HttpServletRequest request,App app) {
        String port = request.getHeader("port");
        String creator = request.getHeader("creator");
        String env = request.getHeader("env");
        String basePath = "http://" + request.getRemoteAddr()+ ":" + port;
        create(app,env,creator,basePath);
    }


    @Transactional
    protected void create(App app, String env, String creator, String basePath) {
        if (appRepository.exits(app.getName())) {
            appRepository.update(app);
        } else {
            appRepository.create(app);
        }
        Environment environment = new Environment();
        environment.setBasePath(basePath);
        environment.setName(env);
        environment.setOwner(creator);
        app.getApis().forEach(api->{
            api.setCreator(creator);
        });
        apiSaveExe.batchCreate(app.getName(),app.getApis());
        environmentRepository.create(app.getName(),environment);
    }
}
